package com.lijian.dns;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * DNS解释定时任务
 * DnsAnalysisTask
 *
 * @author LIJIAN
 * @date 2021/2/1
 */
@Slf4j
@Component
public class DnsAnalysisTask {

    //阿里云dns域名
    @Value("${aliyun-dns.domainNames:}")
    private List<String> domainNames;

    @Resource
    private AliDnsService aliDnsService;

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void execute() {
        if (CollUtil.isNotEmpty(domainNames)) {
            String ipV4 = IPUntils.getOutIPV4(); // 获取公网ip
            for (String domainName : domainNames) {
                String[] split = domainName.split("\\.");
                String rr = split[0];
                String domain = split[1] + "." + split[2];
                List<Record> records = aliDnsService.getRecords(domain);
                for (Record record : records) {
                    if (!record.getValue().equals(ipV4) && rr.equals(record.getRR())) {
                        record.setValue(ipV4);
                        aliDnsService.analysisDns(record);
                        log.info(">>>>>>  域名解析IP: {} ", ipV4);
                    }
                }
            }
        }
    }
}
